import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:intl/intl.dart';
import '../../../data/models/download_record.dart';
import '../controllers/download_controller.dart';
import '../../../widgets/safe_network_image.dart';

// 使用从数据模型导入的DownloadRecord
// 使用从数据模型导入的DownloadStatus

class DownloadView extends GetView<DownloadController> {
  const DownloadView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFEDF3FA),
      appBar: AppBar(
        leading: IconButton(
          onPressed: () {
            Get.back();
          },
          icon: Icon(Icons.arrow_back_ios_new_rounded, size: 32.sp),
        ),
        title: Text(
          '下载列表',
          style: TextStyle(fontSize: 32.sp, fontWeight: FontWeight.w600),
        ),
        centerTitle: true,
        backgroundColor: Colors.transparent,
        foregroundColor: const Color(0xFF333333),
        elevation: 0,
        scrolledUnderElevation: 0,
        surfaceTintColor: Colors.transparent,
        shadowColor: Colors.transparent,
        actions: [
          Obx(
            () => TextButton(
              onPressed: () async {
                await controller.toggleAllDownloads();
              },
              child: Text(
                controller.toggleAllText,
                style: TextStyle(
                  fontSize: 28.sp,
                  color: const Color(0xFF007AFF),
                ),
              ),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          // 筛选标签栏
          _buildFilterTabs(),
          // 下载列表
          Expanded(child: _buildDownloadList()),
        ],
      ),
    );
  }

  /// 构建筛选标签栏
  Widget _buildFilterTabs() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 24.h),
      child: Obx(
        () => Row(
          children: [
            _buildFilterTab('全部', 0, count: controller.downloadRecords.length),
            SizedBox(width: 40.w),
            _buildFilterTab('进行中', 1, count: controller.downloadingCount),
            SizedBox(width: 40.w),
            _buildFilterTab('已完成', 2, count: controller.completedCount),
          ],
        ),
      ),
    );
  }

  /// 构建单个筛选标签
  Widget _buildFilterTab(String title, int index, {int? count}) {
    return Obx(() {
      final isSelected = controller.selectedFilterIndex.value == index;
      return GestureDetector(
        onTap: () {
          controller.changeFilter(index);
        },
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 34.w, vertical: 12.h),
          decoration: BoxDecoration(
            color: isSelected ? const Color(0xFF007AFF) : Colors.white,
            borderRadius: BorderRadius.circular(25.r),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                title,
                style: TextStyle(
                  fontSize: 28.sp,
                  color: isSelected ? Colors.white : const Color(0xFF999999),
                  fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
                ),
              ),
              if (count != null && count > 0) ...[
                SizedBox(width: 8.w),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.h),
                  decoration: BoxDecoration(
                    color:
                        isSelected
                            ? Colors.white.withValues(alpha: 0.3)
                            : const Color(0xFF007AFF).withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(10.r),
                  ),
                  child: Text(
                    count.toString(),
                    style: TextStyle(
                      fontSize: 20.sp,
                      color:
                          isSelected ? Colors.white : const Color(0xFF007AFF),
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      );
    });
  }

  /// 构建下载列表
  Widget _buildDownloadList() {
    return Obx(() {
      final filteredRecords = controller.filteredDownloadRecords;
      final allRecords = controller.downloadRecords;

      print('📋 下载页面调试:');
      print('  总记录数: ${allRecords.length}');
      print('  筛选后记录数: ${filteredRecords.length}');
      print('  当前筛选索引: ${controller.selectedFilterIndex.value}');
      print(
        '  所有记录状态: ${allRecords.map((r) => '${r.deviceName}: ${r.status}').toList()}',
      );

      if (filteredRecords.isEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.download_outlined,
                size: 80.w,
                color: const Color(0xFFCCCCCC),
              ),
              SizedBox(height: 20.h),
              Text(
                '暂无下载内容',
                style: TextStyle(
                  fontSize: 20.sp,
                  color: const Color(0xFF999999),
                ),
              ),
            ],
          ),
        );
      }

      return ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
        itemCount: filteredRecords.length,
        itemBuilder: (context, index) {
          return _buildDownloadItemCard(filteredRecords[index]);
        },
      );
    });
  }

  /// 构建单个下载项卡片
  Widget _buildDownloadItemCard(DownloadRecord record) {
    return GestureDetector(
      onTap: () {
        // 如果视频已完成，点击整个卡片播放视频
        if (record.status == DownloadStatus.completed && record.id != null) {
          controller.playVideo(record.id.toString());
        }
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 20.h),
        padding: EdgeInsets.all(24.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 12.r,
              offset: const Offset(0, 3),
            ),
          ],
        ),
        child: Row(
          children: [
            // 左侧缩略图
            _buildThumbnail(record),
            SizedBox(width: 24.w),
            // 中间信息区域
            Expanded(child: _buildItemInfo(record)),
            SizedBox(width: 20.w),
            // 右侧操作按钮
            Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildActionButton(record),
                SizedBox(height: 12.h),
                _buildDeleteButton(record),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建缩略图 - 使用首帧图
  Widget _buildThumbnail(DownloadRecord record) {
    // 默认图片组件
    final defaultImage = Container(
      width: 212.w,
      height: 142.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        color: const Color(0xFFF5F5F5),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12.r),
        child: Image.asset(
          'assets/images/暂无视频2x.png',
          width: 212.w,
          height: 142.h,
          fit: BoxFit.cover,
        ),
      ),
    );

    // 如果没有封面图URL，直接显示默认图片
    if (record.picUrl.isEmpty) {
      return defaultImage;
    }

    // 有封面图URL时，使用SafeNetworkImage加载，失败时显示默认图片
    return SafeNetworkImage(
      imageUrl: record.picUrl,
      width: 212.w,
      height: 142.h,
      fit: BoxFit.cover,
      borderRadius: BorderRadius.circular(12.r),
      errorWidget: defaultImage, // 加载失败时显示默认图片
    );
  }

  /// 构建项目信息
  Widget _buildItemInfo(DownloadRecord record) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        // 设备名称（第一行）
        Text(
          record.deviceName,
          style: TextStyle(
            fontSize: 28.sp,
            fontWeight: FontWeight.bold,
            color: const Color(0xFF333333),
          ),
          overflow: TextOverflow.ellipsis,
          maxLines: 1,
        ),
        // 时间信息（第二行）- 换行显示
        SizedBox(height: 8.h),
        Text(
          _formatTimeRange(record.startTime, record.endTime),
          style: TextStyle(fontSize: 24.sp, color: const Color(0xFF666666)),
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
        ),
        // 状态信息
        SizedBox(height: 12.h),
        // 根据状态显示不同信息
        if (record.status == DownloadStatus.completed)
          Text(
            record.downloadedSize,
            style: TextStyle(fontSize: 18.sp, color: Color(0xFF999999)),
            overflow: TextOverflow.ellipsis,
          )
        else if (record.status == DownloadStatus.downloading)
          Text(
            '${record.downloadedSize} • ${record.speed}',
            style: TextStyle(fontSize: 18.sp, color: Color(0xFF999999)),
            overflow: TextOverflow.ellipsis,
          )
        else
          Text(
            record.downloadedSize,
            style: TextStyle(fontSize: 18.sp, color: Color(0xFF999999)),
            overflow: TextOverflow.ellipsis,
          ),
        SizedBox(height: 8.h),
        Row(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
              decoration: BoxDecoration(
                color: _getStatusColor(record.status).withOpacity(0.1),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Text(
                _getStatusText(record.status),
                style: TextStyle(
                  fontSize: 16.sp,
                  color: _getStatusColor(record.status),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            if (record.status == DownloadStatus.completed) ...[
              SizedBox(width: 8.w),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                decoration: BoxDecoration(
                  color: Colors.green.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text(
                  'MP4',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: Colors.green,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ],
        ),
        if (record.status == DownloadStatus.downloading ||
            record.status == DownloadStatus.paused) ...[
          SizedBox(height: 21.h),
          // 进度条
          _buildProgressBar(record),
        ],
      ],
    );
  }

  /// 构建进度条
  Widget _buildProgressBar(DownloadRecord record) {
    return Container(
      height: 6.h,
      decoration: BoxDecoration(
        color: const Color(0xFFE0E0E0),
        borderRadius: BorderRadius.circular(3.r),
      ),
      child: FractionallySizedBox(
        widthFactor: record.progress,
        alignment: Alignment.centerLeft,
        child: Container(
          decoration: BoxDecoration(
            color: const Color(0xFF007AFF),
            borderRadius: BorderRadius.circular(3.r),
          ),
        ),
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActionButton(DownloadRecord record) {
    IconData icon;
    Color color;
    VoidCallback onTap;
    String tooltip;

    // 检查record.id是否为null
    if (record.id == null) {
      print('❌ 下载记录ID为null: ${record.deviceName}');
      icon = Icons.error;
      color = const Color(0xFFFF6B6B);
      onTap = () => BotToast.showText(text: '下载记录错误，请删除后重新下载');
      tooltip = '记录错误';
    } else {
      switch (record.status) {
        case DownloadStatus.downloading:
          icon = Icons.pause_circle_filled;
          color = const Color(0xFF007AFF);
          onTap =
              () async => await controller.pauseDownload(record.id.toString());
          tooltip = '暂停下载';
          break;
        case DownloadStatus.waiting:
        case DownloadStatus.paused:
          icon = Icons.play_circle_filled;
          color = const Color(0xFF007AFF);
          onTap =
              () async => await controller.resumeDownload(record.id.toString());
          tooltip = '继续下载';
          break;
        case DownloadStatus.completed:
          icon = Icons.play_circle_filled;
          color = const Color(0xFF00C851);
          onTap = () => controller.playVideo(record.id.toString());
          tooltip = '播放本地MP4视频';
          break;
        case DownloadStatus.failed:
          icon = Icons.refresh;
          color = const Color(0xFFFF6B6B);
          onTap =
              () async => await controller.retryDownload(record.id.toString());
          tooltip = '重试下载';
          break;
      }
    }

    return Tooltip(
      message: tooltip,
      child: GestureDetector(
        onTap: onTap,
        behavior: HitTestBehavior.opaque,
        child: Container(
          padding: EdgeInsets.all(8.w),
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Icon(icon, size: 48.w, color: color),
        ),
      ),
    );
  }

  /// 获取状态颜色
  Color _getStatusColor(DownloadStatus status) {
    switch (status) {
      case DownloadStatus.waiting:
        return const Color(0xFF999999);
      case DownloadStatus.downloading:
        return const Color(0xFF007AFF);
      case DownloadStatus.paused:
        return const Color(0xFFFF9500);
      case DownloadStatus.completed:
        return const Color(0xFF00C851);
      case DownloadStatus.failed:
        return const Color(0xFFFF6B6B);
    }
  }

  /// 获取状态文本
  String _getStatusText(DownloadStatus status) {
    switch (status) {
      case DownloadStatus.waiting:
        return '等待中';
      case DownloadStatus.downloading:
        return '下载中';
      case DownloadStatus.paused:
        return '已暂停';
      case DownloadStatus.completed:
        return '已完成';
      case DownloadStatus.failed:
        return '下载失败';
    }
  }

  /// 格式化时间范围 - 显示日期+文件形式（包含年份）
  String _formatTimeRange(String startTime, String endTime) {
    try {
      // 解析开始时间
      DateTime? startDateTime;
      DateTime? endDateTime;

      // 尝试不同的格式解析
      if (startTime.length == 14 && !startTime.contains(':')) {
        // yyyyMMddHHmmss 格式
        startDateTime = DateTime.parse(
          '${startTime.substring(0, 4)}-${startTime.substring(4, 6)}-${startTime.substring(6, 8)} '
          '${startTime.substring(8, 10)}:${startTime.substring(10, 12)}:${startTime.substring(12, 14)}',
        );
      } else if (startTime.contains('T')) {
        // ISO 8601 格式：2025-11-20T17:37:01
        startDateTime = DateTime.parse(startTime.replaceAll('T', ' '));
      } else if (startTime.contains('-') || startTime.contains('/')) {
        startDateTime = DateTime.parse(startTime.replaceAll('/', '-'));
      }

      if (endTime.length == 14 && !endTime.contains(':')) {
        // yyyyMMddHHmmss 格式
        endDateTime = DateTime.parse(
          '${endTime.substring(0, 4)}-${endTime.substring(4, 6)}-${endTime.substring(6, 8)} '
          '${endTime.substring(8, 10)}:${endTime.substring(10, 12)}:${endTime.substring(12, 14)}',
        );
      } else if (endTime.contains('T')) {
        // ISO 8601 格式：2025-11-20T17:36:55
        endDateTime = DateTime.parse(endTime.replaceAll('T', ' '));
      } else if (endTime.contains('-') || endTime.contains('/')) {
        endDateTime = DateTime.parse(endTime.replaceAll('/', '-'));
      }

      if (startDateTime != null && endDateTime != null) {
        // 格式化日期部分（包含年份）
        final dateFormatter = DateFormat('yyyy-MM-dd');
        final timeFormatter = DateFormat('HH:mm:ss');

        final startDate = dateFormatter.format(startDateTime);
        final startTimeStr = timeFormatter.format(startDateTime);
        final endDate = dateFormatter.format(endDateTime);
        final endTimeStr = timeFormatter.format(endDateTime);

        // 如果是同一天，显示：yyyy-MM-dd HH:mm:ss - HH:mm:ss
        if (startDate == endDate) {
          return '$startDate $startTimeStr - $endTimeStr';
        } else {
          // 不同天，显示完整日期时间
          return '$startDate $startTimeStr\n$endDate $endTimeStr';
        }
      }
    } catch (e) {
      // 解析失败，返回原始格式
      print('时间解析失败: $e, startTime: $startTime, endTime: $endTime');
    }

    return '$startTime - $endTime';
  }

  /// 构建删除按钮
  Widget _buildDeleteButton(DownloadRecord record) {
    // ✅ 下载中和等待中不显示删除按钮
    if (record.status == DownloadStatus.downloading ||
        record.status == DownloadStatus.waiting) {
      return SizedBox(width: 48.w, height: 48.w); // 占位，保持布局一致
    }

    return Tooltip(
      message: '删除下载记录',
      child: GestureDetector(
        onTap: () => _showDeleteConfirmDialog(record),
        behavior: HitTestBehavior.opaque,
        child: Container(
          padding: EdgeInsets.all(8.w),
          decoration: BoxDecoration(
            color: Colors.red.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Icon(Icons.delete_outline, size: 32.w, color: Colors.red),
        ),
      ),
    );
  }

  /// 显示删除确认对话框
  Future<void> _showDeleteConfirmDialog(DownloadRecord record) async {
    final confirmed = await Get.dialog<bool>(
      AlertDialog(
        backgroundColor: Colors.white,
        title: Row(
          children: [
            Text(
              '确认删除',
              style: TextStyle(
                fontSize: 32.sp,
                fontWeight: FontWeight.w600,
                color: Color(0xFF333333),
              ),
            ),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '确定要删除这个下载记录吗？',
              style: TextStyle(fontSize: 28.sp, color: Color(0xFF666666)),
            ),
            SizedBox(height: 12.h),
            Text(
              '设备: ${record.deviceName}',
              style: TextStyle(fontSize: 24.sp, color: Color(0xFF999999)),
            ),
            Text(
              '时间: ${_formatTimeRange(record.startTime, record.endTime)}',
              style: TextStyle(fontSize: 24.sp, color: Color(0xFF999999)),
            ),
            SizedBox(height: 16.h),
            Text(
              '删除后无法恢复，本地文件也会被删除。',
              style: TextStyle(fontSize: 24.sp, color: Colors.red),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: Text(
              '取消',
              style: TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
            ),
          ),
          ElevatedButton(
            onPressed: () => Get.back(result: true),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
            child: Text('删除', style: TextStyle(fontSize: 28.sp)),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      await controller.deleteDownload(record.id.toString());
    }
  }
}
